<template>
    <div class="app-detail">
        <list-layout>
         <div slot="search">
            <el-form :model="queryParams" :inline="true" ref="queryForm" v-show="showSearch" label-width="88px">

                <el-form-item :label="$t('transferRules.currentTactics')">
                    <el-select v-model="queryParams.currentTactics"  clearable  size="small" style="width:130px">
                        <el-option v-for="item in dict.type.NYIQC_RULE_TACTICS" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

            </el-form>
            <div style="display: flex; justify-content: center">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("public.search") }}</el-button>
                <el-button icon="el-icon-refresh" class="resectBtn" size="mini" @click="resetQuery">{{ $t("public.reset") }}</el-button>
            </div>
        </div>

        <div class="app-container">
          <el-row :gutter="20" class="mb8 btnGroup">
               <el-col :span="6">
                    {{ $t('transferRules.ruleCode')+'：'+ ruleData.ruleCode }}
                </el-col>
                <el-col :span="6">
                    {{ $t('transferRules.ruleName')+'：'+ ruleData.ruleName }}
                </el-col>
                <el-col :span="6">
                    {{ $t('inspectionStandards.division')+'：'+ ruleData.divisionName }}
                </el-col>
            </el-row>
            <el-row :gutter="10" class="mb8 btnGroup">
                <el-col :span="1.5">
                    <el-button size="mini" type="primary" @click="handleAdd">
                        {{ $t('btn.tianjia') }}</el-button>
                </el-col>
            </el-row>
            <div class="container-table">
                <el-table class="table-fixed"   ref="multipleTable" :key="incomingKey" v-loading="loading" :height="tableHeight" border
                :data="incomingList"  >

                    <el-table-column :label="$t('transferRules.currentTactics')" sortable  align="left" prop="currentTactics" min-width="120" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                  {{formatNYIQC_RULE(scope.row.currentTactics)}}
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column :label="$t('transferRules.relaxTactics')" sortable  align="left" prop="relaxTactics" min-width="120" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                  {{formatNYIQC_RULE(scope.row.relaxTactics)}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('transferRules.fkCycleType')" sortable  align="left" prop="fkCycleType" min-width="120" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('transferRules.fkTimeCycle')" sortable  align="left" prop="fkTimeCycle" min-width="120" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('transferRules.fkRadius')" sortable  align="left" prop="fkRadius" min-width="120" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('inspectionManagement.QualifiedQuantity')" sortable  align="left" prop="fkCheckNum" min-width="120" :show-overflow-tooltip="true" />

                    <el-table-column :label="$t('transferRules.tightenTactics')" sortable  align="left" prop="tightenTactics" min-width="120" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                  {{formatNYIQC_RULE(scope.row.tightenTactics)}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('transferRules.jyCycleType')" sortable  align="left" prop="jyCycleType" min-width="120" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('transferRules.jyTimeCycle')" sortable  align="left" prop="jyTimeCycle" min-width="120" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('transferRules.jyRadius')" sortable  align="left" prop="jyRadius" min-width="120" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('transferRules.jyCheckNum')" sortable  align="left" prop="jyCheckNum" min-width="120" :show-overflow-tooltip="true" />

                    <el-table-column :label="$t('transferRules.ExecutionTactics')" sortable  align="left" prop="unTactics" min-width="120" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                  {{formatNYIQC_RULE(scope.row.unTactics)}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('transferRules.jyCycleType')" sortable  align="left" prop="unCycleType" min-width="120" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('transferRules.jyTimeCycle')" sortable  align="left" prop="unTimeCycle" min-width="120" :show-overflow-tooltip="true" />
                    
                    <el-table-column :label="$t('public.opera')" fixed="right" align="center" width="140">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                <table-body-btn type="view" :name="$t('home.view')" @click.native="onEdit(scope.row,$t('home.view'))" />
                                <table-body-btn type="edit"  :name="$t('btn.edit')" @click.native="onEdit(scope.row,$t('public.edit'))" />
                                <table-body-btn type="delete" :name="$t('btn.delete')" @click.native="onDelete(scope.row)" />

                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" layout="total, sizes, prev, pager, next, jumper" />
            </div>

        </div>
        </list-layout>

        <div class="submit-footer" >
            <el-button icon="el-icon-close" size="small" class="drawer-close" @click.native="handleClose">{{$t('public.close')}}</el-button>
        </div>
         <!-- 添加 -->
        <el-dialog :title="viewflag" :visible.sync="typeOpen" center top="14vh"  width="1000px" :fullscreen="fullscreen" @close="close">
            <el-form :model="typeModel" size="small" label-suffix=":" ref="detailForm" :rules="rules" label-width="88px">
                <el-row :gutter="24" class="dia">
                    <el-col :span="24">
                        <el-form-item :label="$t('transferRules.currentTactics')" prop="currentTactics">
                            <el-select v-model="typeModel.currentTactics"  :placeholder="$t('public.placeholder',{placeholder: $t('transferRules.currentTactics')})" clearable
                            size="small" style="width:130px" :disabled="viewflag=='查看'">
                                <el-option v-for="item in typelist" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                            <el-tooltip style="margin-left: 5px;" effect="dark" :content="$t('formValidation.forExample')" placement="right">
                                    <i class="el-icon-question" style="font-size:16px;cursor:pointer"></i>
                            </el-tooltip>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-divider content-position="center">{{ $t('transferRules.relaxationTriggerCondition') }}
                            <el-tooltip class="item" effect="dark" :content="$t('formValidation.forExample')" placement="right">
                                    <i class="el-icon-question" style="font-size:16px;cursor:pointer"></i>
                            </el-tooltip>
                        </el-divider>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item :label="$t('transferRules.relaxTactics')">
                            <el-select v-model="typeModel.relaxTactics"  :placeholder="$t('public.select_holder',{select_holder: $t('transferRules.relaxTactics')})" clearable
                            :disabled="viewflag=='查看'" size="small" style="width:130px" @change="clearValidatechange">
                                <el-option v-for="item in typelist" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>

                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item :label="$t('transferRules.timeCycle')" :prop="typeModel.relaxTactics ? 'fkTimeCycle' : 'Empty'">
                            <el-input v-model.number="typeModel.fkTimeCycle" :placeholder="$t('mtool.measuringHolder')"  :disabled="viewflag=='查看'" clearable size="small"  @input="(e)=>isPositiveNumber(e,'fkTimeCycle')"/>
                        </el-form-item>
                    </el-col>
                     <el-col :span="6">
                        <el-form-item :label="$t('transferRules.fkCycleType')"  :prop="typeModel.relaxTactics ? 'fkCycleType' : 'Empty'">
                            <el-select v-model="typeModel.fkCycleType" :placeholder="$t('public.placeholder',{placeholder: $t('transferRules.fkCycleType')})" clearable size="small">
                                <el-option v-for="item in typelist" :key="item.label" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('transferRules.fkRadius')"  :prop="typeModel.relaxTactics ? 'fkRadius' : 'Empty'">
                            <el-input v-model="typeModel.fkRadius" :placeholder="$t('mtool.measuringHolder')"  :disabled="viewflag=='查看'" clearable size="small" @input="(e)=>isPositiveNumber(e,'fkRadius')"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('transferRules.fkCheckNum')"  :prop="typeModel.relaxTactics ? 'fkCheckNum' : 'Empty'">
                            <el-input v-model="typeModel.fkCheckNum" :placeholder="$t('mtool.measuringHolder')" clearable  :disabled="viewflag=='查看'"  size="small" @input="(e)=>isPositiveNumber(e,'fkCheckNum')"/>
                        </el-form-item>
                    </el-col>



                    <el-col :span="24">
                        <el-divider content-position="center">
                            {{ $t('transferRules.tightenTriggerConditions') }}
                            <el-tooltip class="item" effect="dark" :content="$t('formValidation.forExample3')" placement="right">
                                    <i class="el-icon-question" style="font-size:16px;cursor:pointer"></i>
                            </el-tooltip>
                        </el-divider>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item :label="$t('transferRules.tightenTactics')">
                            <el-select v-model="typeModel.tightenTactics"  :placeholder="$t('public.placeholder',{placeholder: $t('transferRules.tightenTactics')})" clearable
                            :disabled="viewflag=='查看'" size="small" style="width:130px"  @change="clearValidatechange2" @clear="clearValidateFN">
                                <el-option v-for="item in typelist" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('transferRules.jyTimeCycle')"  :prop="typeModel.tightenTactics ? 'jyTimeCycle' : 'Empty'">
                            <el-input v-model="typeModel.jyTimeCycle" clearable  :placeholder="$t('mtool.measuringHolder')" :disabled="viewflag=='查看'" size="small"  @input="(e)=>isPositiveNumber(e,'jyTimeCycle')"/>

                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('transferRules.jyCycleType')"  :prop="typeModel.tightenTactics ? 'jyCycleType' : 'Empty'">
                            <el-select v-model="typeModel.jyCycleType" clearable  size="small">
                                <el-option v-for="item in dict.type.NYIQC_CYCLE_TYPE" :key="item.label" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('transferRules.jyRadius')"  :prop="typeModel.tightenTactics ? 'jyRadius' : 'Empty'">
                            <el-input type="number" :step="1" step-strictly :min="0" v-model="typeModel.jyRadius" clearable  :placeholder="$t('public.placeholder',{placeholder: $t('transferRules.jyRadius')})" :disabled="viewflag=='查看'" size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('transferRules.jyCheckNum')"  :prop="typeModel.tightenTactics ? 'jyCheckNum' : 'Empty'">
                            <el-input type="number" :step="1" step-strictly :min="0" v-model="typeModel.jyCheckNum" clearable  :placeholder="$t('public.placeholder',{placeholder: $t('transferRules.jyCheckNum')})" :disabled="viewflag=='查看'" size="small"/>
                        </el-form-item>
                    </el-col>
                    <div style="clear: both;"></div>
                        <el-col :span="6">
                            <el-form-item :label="$t('transferRules.jyTimeCycle')">
                                <el-input v-model="typeModel.unTimeCycle" clearable  :placeholder="$t('mtool.measuringHolder')" :disabled="viewflag=='查看'" size="small"  @input="(e)=>isPositiveNumber(e,'unTimeCycle')"/>

                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item :label="$t('transferRules.jyCycleType')"  :prop="typeModel.unTactics ? 'unCycleType' : 'Empty'">
                                <el-select v-model="typeModel.unCycleType" disabled clearable  size="small">
                                    <el-option v-for="item in dict.type.NYIQC_CYCLE_TYPE" :key="item.label" :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item :label="$t('transferRules.ExecutionTactics')">
                                <el-select v-model="typeModel.unTactics"  :placeholder="$t('public.placeholder',{placeholder: $t('transferRules.ExecutionTactics')})" clearable
                                :disabled="viewflag=='查看'" size="small" style="width:130px"  @change="clearValidatechange3" @clear="clearValidateFN3">
                                    <el-option v-for="item in typelist" :key="item.value" :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    
                </el-row>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitAdd" :loading="loading" v-if="viewflag!='查看'" icon="el-icon-document" size="small">{{$t('public.save')}}</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {mapGetters, mapState} from 'vuex'
import FileUpload from '@/components/FileUpload'
import printerDialog from '@/views/components/printerDialog'
import SelectUserDialog from '@/views/components/SelectUserDialog'
import {skipList,skipAdd,skipEdit,skipDel,getTransferRulesInfo,carryOutList} from "@/api/inspectionManagement/transferRules"
export default {
    name: 'editMaterial',
    dicts: [
       'NYIQC_CYCLE_TYPE',
       'NYIQC_RULE_TACTICS'
    ],
    components: {
        FileUpload,
        printerDialog,
        SelectUserDialog,
    },
    data() {
        var validateNumberOrNAN = (rule, value, callback) => {

                if ((/^[1-9]\d*$/).test(value) || value=="NA") {
                    callback()
                } else {
                    callback(new Error('请输入整数或 NA'))
                }

        }
        var validateNumber = (rule, value, callback) => {
                if ((/^[1-9]\d*$/).test(value) || value=="0") {
                    callback()
                } else {
                    callback(new Error('请输入整数'))
                }
        }
        return {

            factoryList: [],


            showSearch: true,
            tableHeight: 'calc(100vh - 308px)',

            typeOpen: false,
            queryParams:{
                pageNum:1,
                pageSize:10
            },

            typeModel: {
                 jyCycleType:"月",
                 fkCycleType:"月",
                 jyTimeCycle:"",
                 fkTimeCycle:"",
                 relaxTactics:"",
                 unCycleType:"月",
                 unTactics:"",
                 unTimeCycle:""
            },

            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            stemList: [],
            // 总条数
            total: 0,
            // 字典表格数据
            incomingList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            selectRows: [],
            rowifInspect: '',
            // 查询参数

            // 表单参数
            form: {},
            // 表单校验
            rules: {
                currentTactics: [ {  required: true, message: '当前策略不能为空', change: 'blur',}],

                relaxTactics: [ {  required: true, message: '放宽策略不能为空', change: 'blur',}],
                fkTimeCycle: [ { validator: validateNumberOrNAN, trigger: 'blur' },{  required: true }],
                fkCycleType: [ {  required: true, message: '周期类型不能为空', change: 'blur', }],
                fkRadius:[{ validator: validateNumberOrNAN, trigger: 'blur' },{  required: true }],
                fkCheckNum:[{ validator: validateNumberOrNAN, trigger: 'blur' },{  required: true }],

                tightenTactics: [ {  required: true, message: '加严策略不能为空', change: 'blur',}],
                jyTimeCycle: [ { validator: validateNumberOrNAN, trigger: 'blur' },{  required: true, message: '时间周期不能为空' }],
                jyCycleType: [ {  required: true, message: '周期类型不能为空', change: 'blur', }],
                unTactics: [ {  required: true, message: '加严策略不能为空', change: 'blur',}],
                unTimeCycle: [ { validator: validateNumberOrNAN, trigger: 'blur' },{  required: true, message: '时间周期不能为空' }],
                // unCycleType: [ {  required: true, message: '周期类型不能为空', change: 'blur', }],
                jyRadius:[{  required: true, message: '批范围不能为空', change: 'blur', },{ validator: validateNumber, trigger: 'blur' },],
                jyCheckNum:[{ required: true, message: '不合格数不能为空', change: 'blur', },{ validator: validateNumber, trigger: 'blur' },],
                // Empty:[
                //     { required: false, message: '请输入用户名', trigger: 'blur' },
                //     { pattern: /^(NA|\d+)$/, message: '只能输入NA或者数字', trigger: 'blur' }
                // ]

            },
            fullscreen: false,
            incomingKey: 0,
            projectList:[],
            //抽样类型 1：正常，2：放宽，3：加严
            samplingTypeList:[
                {value:"1",label:"正常"},
                {value:"2",label:"放宽"},
                {value:"3",label:"加严"},
            ],
             //触发方式（1：自动触发，2：手动触发）
            triggerModeList:[
                {value:"1",label:"自动触发"},
                {value:"2",label:"手动触发"}
            ],

            ruleData: {},   // 规则详情
            typelist:[],
            viewflag:''
        }
    },
    mounted() {
        this.getRuleInfo()
        this.getList()
        this.gettypeList()
        
    },
    activated() {
        this.getRuleInfo()
        this.getList()
    },

    computed: {
        ...mapGetters(['userId', 'name', 'deptName']),
        // 获取 ruleId && ruleCode
        ruleId(){return this.$route.query.ruleId??''},
        ruleCode(){return this.$route.query.ruleCode??''},
    },

    methods: {
        isPositiveNumber(val,type) {
             if (val) {
                if((/^[1-9]\d*$/).test(val) || val==0){
                    this.typeModel[type] =val
                }else{
                    if (val=='NA' || val=='N') {
                        this.typeModel[type] =''
                    }else{
                        this.typeModel[type] ='NA'
                    }
                }
            }
        },
        iszNumber(val,type) {
             if (val) {
                if((/^[1-9]\d*$/).test(val) || val==0){
                    this.typeModel[type] =val
                }else{
                   this.typeModel[type] =''

                }
            }
        },
        clearValidatechange(e){
            if(!e){
                this.$refs.detailForm.clearValidate(['fkTimeCycle','fkRadius','fkCheckNum']);
            }
        },
        clearValidatechange2(e){
            if(!e){
                this.$refs.detailForm.clearValidate(['jyTimeCycle','jyRadius','jyCheckNum']);
            }
        },
        clearValidatechange3(e){
            if(!e){
                this.$refs.detailForm.clearValidate(['unTimeCycle']);
            }
        },
        // 触发清空事件
        clearValidateFN(){
            this.$refs.detailForm.clearValidate(['jyTimeCycle','jyRadius','jyCheckNum']);
            this.typeModel.jyTimeCycle = ''
            this.typeModel.jyRadius = ''
            this.typeModel.jyCheckNum = ''
        },
        // 触发清空事件3
        clearValidateFN3(){
            this.$refs.detailForm.clearValidate(['unTimeCycle']);
            this.typeModel.unTimeCycle = ''
        },
        formatNYIQC_RULE(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_RULE_TACTICS.find((item) => {
                    return item.value === e
                })
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },
        formatNYIQC_CYCLE(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_CYCLE_TYPE.find((item) => {
                    return item.value === e
                })
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },
        handleQuery(){
            this.queryParams.pageNum = 1
            this.getList()
        },
        /**  类型列表 */
        gettypeList() {
           carryOutList({ruleCode:this.ruleCode}).then((response) => {
                if (response) {
                    var typelist=this.dict.type.NYIQC_RULE_TACTICS
                    // typelist.filter(item=>item.value)
                    var list = response.rows
                    this.typelist=[]
                    for (let i = 0; i < typelist.length; i++) {
                         for (let index = 0; index < list.length; index++) {
                             if(list[index].currentTactics==typelist[i].value){
                                this.typelist.push(typelist[i])
                                break
                             }
                         }
                    }
                    if (this.typelist.length==0) {
                        this.$message.error("当前暂无策略类型")
                    }

                }
            })
        },
         /** 新增按钮操作 */
        handleAdd() {
            this.typeModel= {
                 unCycleType:"月",
                 jyCycleType:"月",
                 fkCycleType:"月",
            }

            this.typeOpen = true
            this.viewflag=this.$t("btn.tianjia")
        },
        close(){
            this.typeModel= {
                 unCycleType:"月",
                 jyCycleType:"月",
                 fkCycleType:"月",
            }
            this.$refs.detailForm.resetFields();
            this.viewflag=''
        },
        // 删除
        onDelete(row) {
            this.$modal.confirm(this.$t('formValidation.doYouConfirmDeletion')).then(() => {
                skipDel(row.id).then((response) => {
                    if (response.code == 200) {
                        this.$modal.msgSuccess(this.$t('tips.deleteSuccess'))
                        this.getList()
                    }
                })
            })
        },
        // 修改
        onEdit(row,flag) {
            this.typeModel=JSON.parse(JSON.stringify(row))
            this.typeModel.unCycleType = '月'
            this.typeOpen = true
            this.viewflag=flag
        },

        // 提交添加
        submitAdd(){
            this.$refs.detailForm.validate((valid) => {
                if (valid) {
                    var data={
                        ...this.typeModel,
                        unCycleType:'月',
                        ruleCode:this.ruleCode
                    }
                    var action=this.typeModel.id ? skipEdit : skipAdd
                    action(data).then(res=>{
                        this.$message.success(this.typeModel.id?this.$t('formValidation.successfullyModified') : this.$t('formValidation.addedSuccessfully'))
                        this.getList()
                        this.typeOpen=false
                    })
                } else {
                    // this.$modal.msgError(this.$t('formValidation.theBasicInformationIsIncomplete'))

                }
            })
        },

        /**  类型列表 */
        getList() {
            this.loading = true
            var data={
                ...this.queryParams,
                ruleCode:this.ruleCode
            }
            skipList(data).then((response) => {
                if (response.code==200) {
                    this.incomingList = response.data.rows

                    this.total = response.data.total
                    this.loading = false

                }
            })
        },
        // 取消按钮
        resetQuery() {

            this.queryParams={
                 pageNum:1,
                pageSize:10
            }
            this.getList()
        },

        /** 关闭操作 */
        handleClose(row) {
            this.$router.go(-1)
        },

        /** 获取规则详情  */
        getRuleInfo(){
            getTransferRulesInfo(this.ruleId).then(res=>{
                console.log('获取规则详情',res)
                if(res.code == 200 && res.data.id == this.ruleId) this.ruleData = res.data
            })
        }
    },
}
</script>
<style lang="scss" scoped>@import './index.scss';</style>
